
# make DIST=<dist> ARCH=<arch> KERNEL=<kernel> DRV_NAME=<driver> OUT=<out>

include .config

NS := PS

ROOT_DIST := "/mnt/nfs/dists"
PKG_TOOL := PackageModules.sh
RUNNING_ARCH := $(shell uname -m)

ifneq (,${${NS}_ROOT_DIST})
    ROOT_DIST := ${${NS}_ROOT_DIST}
endif

ifeq (,${${NS}_DIST})
    BUILD_DIST := $(shell echo ${DISTS})
else
    BUILD_DIST := ${${NS}_DIST}
endif

ifeq (,${${NS}_DRV_DIR})
    DRV_DIR := ${CURDIR}/drivers
else
    DRV_DIR := ${${NS}_DRV_DIR}
endif

ifeq (,${${NS}_DRV_OUT})
    OUT := ${DRV_DIR}/out
else
	OUT := ${${NS}_DRV_OUT}
endif

#FIXME: we need to check the running arch to make sure the local env is able to build the request arch.
ifeq (,${${NS}_ARCH})
    BUILD_ARCH := $(shell echo ${ARCHES})
else
    BUILD_ARCH := ${${NS}_ARCH}
endif

ifeq (,${PKG_TOOL_TARGZ})
    PKG_TOOL_TARGZ := ${POWERP2VROOT}/tools/BuildModulePackage/PackageModules.tar.gz
endif



QUIET := @
QUIET_OPT := -s
ifeq (0,${${NS}_QUIET})
    QUIET :=
	QUIET_OPT :=
endif

DRV_BUILD_COMMAND := _ret=0; \
	for dist in ${BUILD_DIST}; do \
		for arch in ${BUILD_ARCH}; do \
			if [ -d ${ROOT_DIST}/$$dist/$$arch ]; then \
				echo "$$message for $$dist $$arch ..."; \
				${CURDIR}/scripts/chrootsh -b ${CURDIR} -d ${DRV_DIR} -o ${OUT} -r ${ROOT_DIST}/$$dist/$$arch make ${QUIET_OPT} -C /drv_repo -f Makefile.chroot ${NS}_DRV_NAME=${${NS}_DRV_NAME} ${NS}_KERNEL=${${NS}_KERNEL} $$command; _ret=$$?; \
				if [ $$_ret -eq 2 ]; then \
				    break 2; \
				fi; \
			fi; \
		done; \
	done; \
	if [ $$_ret -eq 2 ]; then \
		echo "[build] was interrupted"; \
	    false; \
	fi

all: build

${CURDIR}/bin/PackageModules/${PKG_TOOL}: ${PKG_TOOL_TARGZ}
	@echo "Prepare Package Tool"
	-${QUIET}mkdir -p ${CURDIR}/bin/PackageModules
	${QUIET}cd ${CURDIR}/bin/PackageModules; tar xzvf ${PKG_TOOL_TARGZ}
	${QUIET}touch -r ${PKG_TOOL_TARGZ} ${CURDIR}/bin/PackageModules/${PKG_TOOL} 

build: ${CURDIR}/bin/PackageModules/${PKG_TOOL}
	@echo "Build results are saved in ${OUT}"
	-@mkdir ${DRV_DIR} 2>/dev/null
	-@mkdir ${OUT} 2>/dev/null
	${QUIET}message="Build drivers ";command=;${DRV_BUILD_COMMAND}

clean: 
	-${QUIET}message="Clean build results ";command=clean;${DRV_BUILD_COMMAND}
